package ch.ethz.fcl.metrobuzz.data.transit;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ch.ethz.fcl.metrobuzz.data.MBData;

/**
 * transitLine contains transitRoute
 * 
 * @author ZengWei
 * 
 */
public class TransitLine {
	private MBData data;

	private PublicTransit network;
	private String id;

	private ArrayList<TransitRoute> routes;
	private Map<String, TransitRoute> routesMap;

	// record the direction to transit route map
	private Map<Integer, TransitRoute> directionRouteMap;

	public TransitLine(MBData data, PublicTransit network, String id) {
		this.data = data;
		this.network = network;
		this.id = id;
		routes = new ArrayList<TransitRoute>();
		routesMap = new HashMap<String, TransitRoute>();
		directionRouteMap = new HashMap<Integer, TransitRoute>();
	}

	public PublicTransit getTransitNetwork() {
		return network;
	}

	public void addRoute(TransitRoute route) {
		if (!routes.contains(route)) {
			routes.add(route);
			routesMap.put(route.getId(), route);
		}
	}

	public String getId() {
		return id;
	}

	public TransitRoute getRoute(String routeId) {
		routeId = routeId.replace("-p", "");
		TransitRoute route;
		if (!routesMap.containsKey(routeId)) {
			route = new TransitRoute(data, this, routeId);
		} else
			route = routesMap.get(routeId);

		return route;
	}

	public ArrayList<TransitRoute> getRoutes() {
		return routes;
	}

	public TransitRoute getRoute(int direction, Stop start, Stop end) {
		TransitRoute route = directionRouteMap.get(direction);

		if (route == null) {
			for (TransitRoute r : routes) {
				List<Stop> stops = r.getStops();
				int startIndex = stops.indexOf(start);
				int endIndex = -1;

				// cannot find stop in this route
				if (startIndex == -1)
					continue;

				for (int i = startIndex; i < stops.size(); i++) {
					if (stops.get(i).equals(end)) {
						endIndex = i;
					}
				}

				// cannot find stop in this route
				if (endIndex == -1)
					continue;

				if (endIndex > startIndex) {
					route = r;
					if (!start.getId().equals(end.getId()))
						directionRouteMap.put(direction, r);
					break;
				}
			}
		}
		return route;
	}

	public void printRoutes() {
		System.out.println("Line: " + id);
		System.out.print("Routes: ");
		for (int i = 0; i < routes.size(); i++) {
			System.out.print(routes.get(i).getId() + " ");
			routes.get(i).printStops();
		}
		System.out.println();
	}
}
